import { SessionGuard } from '@/guard/session.guard';
import {
  Body,
  Controller,
  Delete,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Post,
  Put,
  Query,
  Req,
  Session,
  UseGuards,
} from '@nestjs/common';
import { UserService } from '../user/user.service';
import { Request as HttpRequest } from 'express';
import { SessionType } from '@/types';
import {
  CreateInventoryHistoryRequest,
  GetBrandsRequest,
  UpdateInventoryHistoryRequest,
} from './dto/request.dto';
import { ResponseBody, ResponseCode } from '@/utils/ResponseCode';
import { Brand as BrandEntity } from '@/entity/Brand';
import { InventoryHistoryService } from './inventory-history.service';
import { InventoryHistory as InventoryHistoryEntity } from '@/entity/InventoryHistory';

@UseGuards(SessionGuard)
@Controller('inventory-history')
export class InventoryHistoryController {
  constructor(
    private readonly inventoryHistoryService: InventoryHistoryService,
    private readonly userService: UserService,
  ) {}

  @Get()
  async getInventoryHistory(
    @Query() query: GetBrandsRequest,
    @Req() request: HttpRequest,
    @Session() session: SessionType,
  ) {
    // 接口鉴权
    await this.userService.verifyPermission(request, session.username);
    const { current, pageSize, ...findWhere } = query;
    const { list, total } = await this.inventoryHistoryService.findAllAndCount(
      findWhere,
      {
        current,
        pageSize,
      },
    );
    return new ResponseBody<{
      total: number;
      list: InventoryHistoryEntity[];
    }>({
      data: {
        total,
        list,
      },
      message: '获取库存记录列表成功',
    });
  }

  // 创建库存记录 start
  @Post()
  async createInventoryHistory(
    @Body() requestBody: CreateInventoryHistoryRequest,
    @Req() request: HttpRequest,
    @Session() session: SessionType,
  ) {
    // 接口鉴权
    await this.userService.verifyPermission(request, session.username);
    // 创建记录
    try {
      const {
        brandId,
        description,
        price,
        type,
        nub,
        customerId,
        marketPrice,
      } = requestBody;
      const inventoryHistoryId =
        await this.inventoryHistoryService.createInventoryHistory({
          brandId,
          description,
          price,
          type,
          nub,
          customerId,
          marketPrice,
        });
      // 返回创建的品牌id
      return new ResponseBody<number>({
        message: '创建库存记录成功',
        data: inventoryHistoryId,
      });
    } catch (error) {
      // 事务抛出错误的兜底
      throw new HttpException(
        {
          message: error,
          code: ResponseCode.Fail,
          data: null,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
  // 创建库存记录 end

  // 更新库存记录 start
  @Put(':id')
  async updateInventoryHistory(
    @Body() requestBody: UpdateInventoryHistoryRequest,
    @Req() request: HttpRequest,
    @Session() session: SessionType,
    @Param('id') inventoryHistoryId: number,
  ) {
    // 接口鉴权
    await this.userService.verifyPermission(request, session.username);
    const { description, price, type, nub, customerId, marketPrice } =
      requestBody;
    try {
      await this.inventoryHistoryService.updateInventoryHistory(
        inventoryHistoryId,
        {
          description,
          price,
          type,
          nub,
          customerId,
          marketPrice,
        },
      );
      return new ResponseBody('更新库存记录信息成功');
    } catch (error) {
      // 事务抛出错误的兜底
      throw new HttpException(
        {
          message: error,
          code: ResponseCode.Fail,
          data: null,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
  // 更新库存记录 start

  @Delete(':id')
  async deleteInventoryHistory(
    @Body() requestBody: UpdateInventoryHistoryRequest,
    @Req() request: HttpRequest,
    @Session() session: SessionType,
    @Param('id') inventoryHistoryId: number,
  ) {
    // 接口鉴权
    await this.userService.verifyPermission(request, session.username);
    try {
      await this.inventoryHistoryService.deleteInventoryHistory(
        inventoryHistoryId,
      );
      return new ResponseBody('删除库存记录信息成功');
    } catch (error) {
      // 事务抛出错误的兜底
      throw new HttpException(
        {
          message: error,
          code: ResponseCode.Fail,
          data: null,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}
